<template>
    <div>
        <div style="margin: 10px 0">
            <el-form :model="pagequery" ref="queryForm" size="small" :inline="true" label-width="68px">
                <el-form-item label="文件名称" prop="title">
                    <el-input
                            v-model="pagequery.fileName"
                            placeholder="请输入文件名称"
                            clearable
                            style="width: 240px;"
                            @keyup.enter.native="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="文件类型" prop="status">
                    <el-select
                            v-model="pagequery.fileType"
                            placeholder="请选择文件类型"
                            clearable
                            style="width: 240px"
                    >
                        <el-option
                                v-for="filetype in dict.type.sys_file_type"
                                :key="filetype.value"
                                :label="filetype.label"
                                :value="filetype.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="操作时间">
                    <el-date-picker
                            v-model="dateRange"
                            style="width: 240px"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            type="daterange"
                            range-separator="-"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            @change="dateFormat"
                            :default-time="['00:00:00', '23:59:59']"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="load">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="reset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div style="margin: 10px 0">
            <el-button
                    type="primary"
                    plain
                    icon="el-icon-top"
                    size="mini"
                    @click="showUploadDialog"
            >点击上传</el-button>
            <el-popconfirm
                    class="ml-5"
                    confirm-button-text='确定'
                    cancel-button-text='我再想想'
                    icon="el-icon-info"
                    icon-color="red"
                    title="您确定批量删除这些数据吗？"
                    @confirm="delBatch"
            >
                <el-button style="margin: 0 5px" icon="el-icon-delete" size="mini" type="danger" slot="reference" plain>批量删除</el-button>
            </el-popconfirm>
        </div>
        <el-table :data="tableData" border stripe v-loading="loading"
                  @selection-change="handleSelectionChange">

            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="ID" width="80"></el-table-column>
            <el-table-column prop="fileName" width="160" label="文件名称" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="fileType" align="center" label="文件类型">
                <template v-slot="scope">
                    <dict-tag :options="dict.type.sys_file_type" :value="scope.row.fileType"/>
                </template>
            </el-table-column>
            <el-table-column prop="fileSize" label="文件大小(mb)">
                <template slot-scope="scope">
                    {{ scope.row.fileSize | transformByte }}
                </template>
            </el-table-column>
            <el-table-column prop="nickName" label="上传用户" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column prop="createTime" label="上传时间"></el-table-column>
            <el-table-column width="80" label="启用">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.enable" active-color="#13ce66" inactive-color="#ccc"
                               @change="changeEnable(scope.row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="200" align="center">
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            type="text"
                            @click="lookonline(scope.row.url)"
                            slot="reference"><i class="el-icon-view"></i>预览
                    </el-button>
                    <el-button
                            size="mini"
                            type="text"

                            @click="download(scope.row.url,scope.row.fileType)"
                            slot="reference"><i class="el-icon-download"></i>下载
                    </el-button>
                    <el-popconfirm
                            confirm-button-text='确定'
                            cancel-button-text='我再想想'
                            icon="el-icon-info"
                            icon-color="red"
                            title="您确定删除吗？"
                            @confirm="del(scope.row)"
                    >
                        <el-button style="margin: 0 10px" size="mini"
                                   type="text"
                                   slot="reference"><i class="el-icon-delete"></i>删除
                        </el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <div style="padding: 10px 0">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pagequery.pageNum"
                    :page-sizes="[2, 5, 10, 20]"
                    :page-size="pagequery.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>
        <FileUpload :fileTableVisible="fileTableVisible" @uploadFileList="uploadFileList"
                    @changeFileDialogVisible="changeFileDialogVisible"></FileUpload>
    </div>
</template>

<script>
    import FileUpload from "@/components/FileUpload";
    import streamSaver from "streamsaver"
    import {getFilesPage, delFilesByIds, delFileById, updateFile} from '@/api/system/file'

    export default {
        name: "File",
        components: {FileUpload},
        dicts:['sys_file_type'],
        data() {
            return {
                dateRange: '',
                // 遮罩层
                loading: true,
                fileTypes: [{label: '图片', value: 'image'}, {label: '文本', value: 'txt'}, {
                    label: '视频',
                    value: 'video'
                }, {label: '音频', value: 'radio'}, {label: 'Excel', value: 'excel'}, {
                    label: 'Word',
                    value: 'word'
                }, {label: 'pdf', value: 'pdf'}, {label: 'PPT', value: 'ppt'}, {label: '其他', value: 'other'}],
                pagequery: {  //分页查询条件
                    pageNum: 1,
                    pageSize: 5,
                },
                fileTableVisible: false,
                uploadHeaders: localStorage.getItem("token"),
                tableData: [],
                multipleSelection: [],
                total: 0,
                headers: localStorage.getItem('token'),
            }
        },
        created() {
            this.load()
        },
        methods: {
            showUploadDialog() {
                //如果有文件没有上传成功就保留这个文件，这样下次打开弹框还有记录
                this.fileTableVisible = true
            },
            changeFileDialogVisible(value) {
                this.fileTableVisible = value
            },
            uploadFileList() {
                this.load()
            },
            load() {
                this.loading = true
                getFilesPage(this.pagequery).then(res => {
                    this.tableData = res.data.records
                    this.total = res.data.total
                    this.loading = false
                })
            },
            changeEnable(row) {
                updateFile(row).then(res => {
                    if (res.code === 200) {
                        this.$message.success("操作成功")
                    }
                })
            },
            del(file) {
                delFileById(file).then(res => {
                    if (res.code === 200) {
                        this.$message.success("删除成功")
                        this.load()
                    }
                })
            },
            handleSelectionChange(val) {
                this.multipleSelection = val
            },
            delBatch() {
                if (this.multipleSelection.length === 0) {
                    this.$message.warning("请选择删除的文件")
                    return
                }
                delFilesByIds(this.multipleSelection).then(res => {
                    if (res.code === 200) {
                        this.$message.success("批量删除成功")
                        this.load()
                    }
                })
            },
            reset() {
                this.dateRange=''
                this.pagequery = {
                    pageNum: 1,
                    pageSize: 5,
                }
                this.load()
            },
            handleSizeChange(pageSize) {
                this.pagequery.pageSize = pageSize
                this.load()
            },
            handleCurrentChange(pageNum) {
                this.pagequery.pageNum = pageNum
                this.load()
            },

            // 下载文件
            download(url) {
                const filename = url.substring(url.lastIndexOf('/') + 1)
                // 创建一个可写流
                var fileStream = streamSaver.createWriteStream(filename);
                // 下载文件
                fetch(url).then((response) => {
                    // 获取响应流
                    var reader = response.body.getReader();
                    // 创建可读流
                    var stream = new ReadableStream({
                        start: function (controller) {
                            // 读取响应流
                            return pump();

                            function pump() {
                                return reader.read().then((result) => {
                                    // 如果已经读取完毕，则关闭流
                                    if (result.done) {
                                        controller.close();
                                        return;
                                    }
                                    // 发送数据块
                                    controller.enqueue(result.value);
                                    // 更新下载进度
                                    // this.progress = Math.round((fileStream.bytesWritten / response.headers.get('Content-Length')) * 100);
                                    // 继续读取
                                    return pump();
                                });
                            }
                        }
                    });
                    // 将可读流写入可写流
                    stream.pipeTo(fileStream);
                });
            },
            lookonline(url) {
                console.log(url)
               // window.open('http://47.96.133.5:8012/onlinePreview?url=' + encodeURIComponent(Base64.encode(url)));
                window.open('http://127.0.0.1:8012/onlinePreview?url=' + encodeURIComponent(Base64.encode(url)));
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.load();
            },
            //获取时间区间方法
            dateFormat(picker) {
                this.pagequery.startTime = picker[0]
                this.pagequery.endTime = picker[1]
            },
        },
        filters: {
            transformByte(size) {
                if (!size) {
                    return '0B'
                }
                const unitSize = 1024
                if (size < unitSize) {
                    return size + ' B'
                }
                // KB
                if (size < Math.pow(unitSize, 2)) {
                    return (size / unitSize).toFixed(2) + ' K';
                }
                // MB
                if (size < Math.pow(unitSize, 3)) {
                    return (size / Math.pow(unitSize, 2)).toFixed(2) + ' MB'
                }
                // GB
                if (size < Math.pow(unitSize, 4)) {
                    return (size / Math.pow(unitSize, 3)).toFixed(2) + ' GB';
                }
                // TB
                return (size / Math.pow(unitSize, 4)).toFixed(2) + ' TB';
            },
            transformType(filename) {
                return filename.substr(filename.lastIndexOf('.') + 1)
            }
        }
    }
</script>

<style scoped>

</style>
